from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app


class MainPage(webapp.RequestHandler):
    
    
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Hello, webapp World!')

from authorization.oauth import OAuth
from sql.sqlbuilder import SQL
import ftclient
from authorization.clientlogin import ClientLogin
USERNAME = 'osu.map@gmail.com'
PASSWORD = 'dlzosumap'

from google.appengine.api import urlfetch
import urllib
from django.utils import simplejson as json

class FetchiFormPage(webapp.RequestHandler):
    def get(self):
        url = "https://www.iformbuilder.com/exzact/dataJSON.php?PAGE_ID=8221&TABLE_NAME=_data10835_curve_db"
        data = self.getTable(url)
        for record in data:
            
            self.response.out.write('<hr>')
            for k, v in record['record'].items(): 
                self.response.out.write('%s: %s <br/>' % (k,v))
    def getTable(self, url):
        
        form_fields = {
          "USERNAME": "ymeng@dlz.com",
          "PASSWORD": "dlzlab"
        }
        form_data = urllib.urlencode(form_fields)
        result = urlfetch.fetch(url=url,
                        payload=form_data,
                        method=urlfetch.POST)
        if result.status_code == 200:
            data = json.loads(result.content)
            return data
        
        
    

class FusionTablePage(webapp.RequestHandler):
    
    def _getClient(self, username, password):
        token = ClientLogin().authorize(username, password)
        self.ftclient = ftclient.ClientLoginFTClient(token)
    
    
    def listtable(self):
        self._getClient(USERNAME,PASSWORD)
        return self.ftclient.query(SQL().showTables())
    
    
    def createtable(self, table):
        self._getClient(USERNAME,PASSWORD)
        #create a table
        table = {'tablename':{'strings':'STRING', 'numbers':'NUMBER', 'locations':'LOCATION'}}
        tableid = int(self.ftclient.query(SQL().createTable(table)).split("\n")[1])
        return tableid
    
    def insertrow(self,tableid, row):
        self._getClient(USERNAME,PASSWORD)
        row = self.ftclient.query(SQL().insert(tableid, row)).split("\n")[1]
        return row
    
    def fusiontable(self):
        
        self._getClient(USERNAME,PASSWORD)
        
        texts = []
       
        
        
        
        table = {'tablename':{'strings':'STRING', 'numbers':'NUMBER', 'locations':'LOCATION'}}
        tableid = self.createtable(table)
        for i in range(20):
            row = {'strings':'mystring %s' % i, 'numbers': i, 'locations':'Palo Alto, CA %s' % i}
            texts.append(self.insertrow(tableid, row))
        #list all the tables
        results = self.ftclient.query(SQL().showTables())
        texts.append(results)
        texts.append(self.ftclient.query(SQL().select(tableid, None, "numbers=10")))
        texts.append(self.ftclient.query(SQL().select(tableid, ['rowid','numbers'], "numbers=10")))
        return texts
    
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        for t in self.fusiontable():
            self.response.out.write(t)
        
        
application = webapp.WSGIApplication([('/', MainPage),
                                      ('/fusiontable', FusionTablePage),
                                      ('/iform', FetchiFormPage)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
